import React, { Component } from 'react';
// import Cart from './Cart';

class CartSample extends Component {
  constructor(props) {
    super(props) // 将父组件引用处声明的属性加入子类的this.props。例子里的title：<CartSample title='我的购物车'></CartSample>
    this.state = { // 声明组件的状态，类似与vue组件的data
      goods: [ // 商品列表
        { id: 1, name: 'web全栈架构师' },
        { id: 2, name: 'python全栈架构师' }
      ],
      form: { // 表单
        good: '' // 商品
      },
      cart: [] // 购物车
    }

    this.handleGoodAdd = this.handleGoodAdd.bind(this) // 将非箭头函数的handleGoodAdd方法的this指针指向react组件的this
  }
  handleGoodChange = e => { // 商品输入框的change方法
    this.setState({ // 更新组件的state（状态）。this.setState(obj || fn)
      form: {
        good: e.target.value
      }
    })
  }
  handleGoodAdd(e) { // 新增商品的方法
    const goods = [...this.state.goods, {
      id: this.state.goods.length + 1,
      name: this.state.form.good
    }]

    this.setState({ goods });
  }

  handleCartAddTo = good => { // 添加入购物车
    const cart = [...this.state.cart];
    const index = cart.findIndex(n => n.id === good.id);
    const item = cart[index];
    if (item) {
      cart.splice(index, 1, { ...item, count: item.count += 1 })
    } else {
      cart.push({ ...good, count: 1 });
    }
    this.setState({ cart });
    console.log(this.state.cart)
  }

  render() { // 渲染jsx的函数
    return (
      <div>
        {this.props.title && <h1>{this.props.title}</h1>}
        <div>
          <div>商品：{this.state.form.good}</div>
          <input type="text" value={this.state.form.good} onChange={this.handleGoodChange} />
          <button onClick={this.handleGoodAdd}>添加商品</button>
        </div>
        <ul style={{ textAlign: 'right', paddingRight: '100px' }}>
          {this.state.goods.map(good => (
            <li key={good.id}>
              {good.name} <button onClick={() => this.handleCartAddTo(good)}>加入购物车</button>
            </li>
          ))}
        </ul>
        <Cart data={this.state.cart}></Cart>
      </div>
    );
  }
}
export default CartSample;

function Cart({ data = [] }) {
  return (
    <div style={{
      display: 'flex',
      justifyContent: 'center'
    }}>
      < table>
        <thead>
          <tr>
            <td>id</td>
            <td>名称</td>
            <td>数量</td>
          </tr>
        </thead>
        <tbody>
          {
            data.map(good => (
              <tr key={good.id}>
                <td>{good.id}</td>
                <td>{good.name}</td>
                <td>{good.count}</td>
              </tr>
            ))
          }
        </tbody>
      </table >
    </div >
  )
}